package com.gpj.sqlbuilder.template;

import org.apache.commons.lang3.StringUtils;

/**
 * @className ChooseTemplate
 * @description TODO
 * @author GPJ
 * @date 2021/4/16 20:49
 * @version 1.0
 **/
public class ChooseTemplate extends ElementTemplate{
	private static final String CHOOSE_START_MARK = "<if>";
	private static final String CHOOSE_TAIL_MARK = "</if>";

	private static final String ATTRIBUTE_KEY_TEST = "test";

	public ChooseTemplate(int start, int tail, Template parent) {
		super(start, tail, parent);
	}

	@Override
	protected String getStartMark() {
		return CHOOSE_START_MARK;
	}

	@Override
	protected String getTailMark() {
		return CHOOSE_TAIL_MARK;
	}

	@Override
	protected void doBuild() {
		String test = getAttribute(ATTRIBUTE_KEY_TEST, "");
		if(StringUtils.isBlank(test)) return;

		test = AnalysisFunction(new StringBuffer(test.trim())).toString();
		test = AnalysisVariable(new StringBuffer(test.trim())).toString();

		String[] tests = test.split(" ");


		boolean result = true;
		for (int i = 0; i < tests.length; i += 2) {
			if(i == 0){
				result = result && isTrue(tests[i]);
				continue;
			}

			if(StringUtils.equals("and", tests[i - 1].trim())){
				result = result && isTrue(tests[i]);
			}else{
				result = result || isTrue(tests[i]);
			}
		}

		if (result && !children.isEmpty()) {
			for(Template child : children){
				child.build();
				sql.append(child.getSql());
			}
		}
	}

	private boolean isTrue(String test){
		return StringUtils.equals("true", test);
	}
}
